import {createReducer, on} from '@ngrx/store';
import {ListActions} from '../actions/list.actions';

export interface State {
  list: {
    id: number,
    name: string,
    age: number
  }[]
}

export const initialState: State = {
  list: [{
    id: 1,
    name: 'zhang san',
    age: 18
  }]
};

let counter = 1;

function generateId() {
  return ++counter;
}

export const listReducer = createReducer(
  initialState,
  on(ListActions.addLists, (state, {data}) => ({list: [...state.list, {id: generateId(), ...data}]})),
  on(ListActions.updateLists, (state, {data}) => {
    const {id} = data;
    let list = state.list;
    list = list.map(v => {
      if (v.id === id) {
        return data
      }
      return v
    })
    return {list}
  }),
  on(ListActions.deleteLists, (state, {data}) => {
    const {id} = data;
    let list = state.list;
    list = list.filter(v => v.id !== id)
    return {list}
  }),
  on(ListActions.deleteMultipleLists, (state, {data}) => {
    let arrId = data.map((v: { id: number; })=>v.id);
    let list = state.list;
    list = list.filter(v => !arrId.includes(v.id))
    return {list}
  })
);

